package com.cc.intercepter;

import com.alibaba.fastjson.JSONObject;
import com.cc.common.utils.ResponseData;
import com.cc.user.entity.UserEntity;
import com.cc.utils.JwtUtils;
import com.cc.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class RedisSessionInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        return true;
//
        if(!RequestUtil.checkAgentIsMobile(request)){
            return true;
        }
        HttpSession session = request.getSession();
        //用户未登录
        UserEntity user = (UserEntity) session.getAttribute("loginuser");
        if (user == null) {
            userDontLogin(response);
            return false;
        }
        //用户已在其他地方登录
        String oldSessionId = redisTemplate.opsForValue().get("user:" + user.getMobile());
        if (!oldSessionId.equals(session.getId())) {
            userLoginToOtherAddress(response);
            return false;
        }
        return true;
    }

    private void userDontLogin(HttpServletResponse response)
    {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try
        {
            ResponseData responseData = new ResponseData(401, "用户未登录", "", false);
            response.getWriter().print(JSONObject.toJSON(responseData));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    private void userLoginToOtherAddress(HttpServletResponse response)
    {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try
        {
            ResponseData responseData = new ResponseData(401, "用户已在其他地方登录", "", false);
            response.getWriter().print(JSONObject.toJSON(responseData));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
